// 通用函数
import useClipboard from 'vue-clipboard3';
import { ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';

//百分比格式化
export function percentFormat(row: any, column: number, cellValue: any) {
	return cellValue ? `${cellValue}%` : '-';
};
//列表日期时间格式化
export function dateFormatYMD(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	return formatDate(new Date(cellValue), 'yyyy-MM-dd');
};
//列表日期时间格式化
export function dateFormatYMDHMS(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	return formatDate(new Date(cellValue), 'yyyy-MM-dd HH:mm:ss');
};
//列表日期时间格式化
export function dateFormatHMS(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	let time = 0;
	if (typeof row === 'number') time = row;
	if (typeof cellValue === 'number') time = cellValue;
	return formatDate(new Date(time * 1000), 'HH:mm:ss');
};
// 小数格式化
export function scaleFormat(value: any = 0, scale: number = 4) {
	return Number.parseFloat(value).toFixed(scale);
};
// 小数格式化
export function scale2Format(value: any = 0) {
	return Number.parseFloat(value).toFixed(2);
};
// 点击复制文本
export function copyText(text: string) {
	const { toClipboard } = useClipboard();
	return new Promise((resolve, reject) => {
		try {
			//复制
			toClipboard(text);
			//下面可以设置复制成功的提示框等操作
			ElMessage.success('复制成功');
			resolve(text);
		} catch (e) {
			//复制失败
			ElMessage.error('复制失败');
			reject(e);
		}
	});
};
/**
 * 线性数据转成树形数据
 * @param data 数组数据[]
 * @param id default='id'
 * @param pid default='parentId'
 * @param children default='children'
 */
export function lineToTreeData(data: any, id?: string, pid?: string, children?: string) {
	if(!data || !(data instanceof Array)){
		return null;
	}
	id = id || 'id';
	pid = pid || 'parentId';
	children = children || 'children';
	let cloneData = JSON.parse(JSON.stringify(data));

	//遍历所有数据找到所有的根节点
	let rootIds = [], results = [];
	for(let i = 0; i < cloneData.length; i++){
		let isRoot = true;
		for(let j = 0; j < cloneData.length; j++){
			if(cloneData[i][pid] == cloneData[j][id]){
				isRoot = false;
				break;
			}
		}
		if(isRoot){
			rootIds.push(cloneData[i][pid]);
		}
	}

	rootIds = Array.from(new Set(rootIds));//去重

	for(let k = 0; k < rootIds.length; k++){
		let pvalue = rootIds[k];
		let result = cloneData.filter((father: any) => {
			let arr = cloneData.filter((child: any) => father[id] == child[pid]);
			arr.length > 0 ? father[children] = arr : father[children] = undefined;
			return father[pid] == pvalue;
		});
		results.push(...result);//合并
	}

	return results;
};